package com.freesun.shop.task;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;

/**
 * 定时任务
 */
@Component
public class WechatTokeRefreshTask {

    public static String token=null;
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    private static Logger logger = LoggerFactory.getLogger(WechatTokeRefreshTask.class);
    @Autowired
    private RestTemplate restTemplate;

    @Value("${wechat.push.app.id}")
    private String appId;
    @Value("${wechat.push.app.secret}")
    private String secret;

    @PostConstruct
    public void initToken() {
        logger.info("初始化一个token");
        String result = restTemplate.getForObject(String.format(ACCESS_TOKEN_URL, appId, secret), String.class);
        JSONObject obj = JSONUtil.parseObj(result);
        if (null != obj&&obj.containsKey("access_token")) {
            token=obj.getStr("access_token");
            logger.info("获取token成功,值为:{}",token);
        }else {
            logger.info("获取token失败，原因为:{}",result);
        }
    }

    /**initialDelay 项目启动多少秒后开始
     * fixedRate  一以固定的速率开始执行
     */
    @Scheduled(initialDelay = 7100*1000,fixedRate = 7100*1000)
    public void refresh() {
        logger.info("定时任务开始获取Token");
        initToken();
    }

}
